import axios from 'axios'
import { storeToRefs } from 'pinia'

import { BASE_URL, TIMEOUT } from './config'
import { useLodingStore } from '@/stores/modules/loading'

const loadingStore = useLodingStore()
const { isLoading } = storeToRefs(loadingStore)


class XBRequest {
  constructor(baseURL, timeout = 10000) {
    this.instance = axios.create({
      baseURL,
      timeout
    })
    // 拦截器
    this.instance.interceptors.request.use((config) => {
      isLoading.value = true
      return config
    }, (error) => {
      return error
    })
    this.instance.interceptors.response.use((res) => {
      isLoading.value = false
      return res
    }, (error) => {
      setInterval(() => {
        isLoading.value = false
      }, 5000)
      return error
    })
  }
  // 发送网络请求
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  }

  get(config) {
    return this.request({ ...config, method: "get" })
  }

  post(config) {
    return this.request({ ...config, method: "post" })
  }
}

export default new XBRequest(BASE_URL, TIMEOUT)

